<?php
/**
* @file Userm.php
* @synopsis  用户操作
* @author Yee, <rlk002@gmail.com>
* @version 1.0
* @date 2015-03-09 10:09:59
*/

defined('BASEPATH') OR exit('No direct script access allowed');

class Userm extends CI_Model
{
    const USERINFO_ALL_KEY = 'getUserInfoALLById_1';
    const USERINFO_BYID_KEY = 'getUserInfoById_2';

    const ERROR_TRY_COUNT_PAY_PASSWD = 5;           // 交易密码错误尝试最大值

	function __construct()
	{
		parent::__construct();

		$this->load->library('phpmail');
		$this->load->model('rssm');
        $this->load->Model("authenticatem");
        $this->load->Model("verifiedm");
        $this->load->Model("utilm");
        $this->load->Model("expertm");
        $this->load->Model("imapim");
		$this->load->Model("followm");
	}

	public function getUserInfoById($id,$nocache=0)
	{
        $userinfo = array();

    	$key = self::USERINFO_BYID_KEY. $id;

        $userinfo = $this->mc->get($key);
		if($userinfo && $nocache == 0)
		{
			//do nothing
		}
		else
		{
			$data_content = $this->db->select()->from('ml_fellow')->where('id',$id)->get()->result_array();
            $userinfo = $data_content[0];
            $userinfo['head_ico'] = ret_fullpath_url($userinfo['head_ico']);
            $userinfo['is_expert'] = $this->transIsExpert($userinfo['user_level']);
            $this->mc->save($key,$userinfo, 10*60);
		}
		return $userinfo;
	}

	public function getUserInfoByUserName($userName)
	{
		return $this->db->select()->from('ml_fellow')->where('username',$userName)->get()->result_array();
	}

	public function getUserInfoByEmail($email)
	{
		return $this->db->select()->from('ml_fellow')->where('email',$email)->get()->result_array();
	}

	public function getUserInfoByCellphone($cellphone)
	{
		return $this->db->select()->from('ml_fellow')->where('cellphone',$cellphone)->get()->result_array();
	}

	public function userRegiest($nocheckhpone,$username,$email,$userpwd,$specialty,$thread,$cellphone = '',$invite_code = '',$practice_hospital = '',$hospital_relate=0,$truename,$post_title,$source)
	{
        //这里改为提示具体字段那里为空
        if(!$username)
        {
            return array('code' => -1,'tips' => '请填写用户名');
        }
        if(!$email)
        {
            return array('code' => -1,'tips' => '请填写邮箱');
        }
        if(!$userpwd)
        {
            return array('code' => -1,'tips' => '请填写密码');
        }
        if(!($specialty || $thread))
        {
            return array('code' => -1,'tips' => '请选择科室');
        }
		if(!isemail($email))
		{
            w_log('email error '.$email);
			return array('code' => -2,'tips' => '邮箱格式不正确');
		}
		if($this->uid != 31495 && $ilegel = checkstesec($username))  //官方账号 不检查非法字符
		{
			$result = array("code" => -3,'tips' => '用户名含有非法字符"'.$ilegel.'"');
			return $result;
		}
        if($this->uid != 31495 && $ilegel = checkstesec($truename))  //官方账号 不检查非法字符
        {
            $result = array("code" => -3,'tips' => '真实姓名含有非法字符"'.$ilegel.'"');
            return $result;
        }

		$checkuser = $this->getUserInfoByUserName($username);
		if($checkuser && $checkuser[0])
		{
			return array('code' => -4,'tips' => '昵称已存在');
		}
		$checkemail = $this->getUserInfoByEmail($email);
		if($checkemail && $checkemail[0])
		{
			return array('code' => -5,'tips' => '该邮箱已存在');
		}

		if(!in_array($cellphone,$nocheckhpone))
		{
			if($cellphone && $this->checkcellphone($nocheckhpone,$cellphone))
			{
				return array('code' => -6,'tips' => '该手机号已存在');
			}
		}

		$set = array();
		$set['username'] = $username;
		$set['email'] = $email;
		$set['password'] = md5($userpwd);

		//android 这里字段错了 先做个兼容吧
		$vid = str_replace(".", "", $this->softversion);
        $vid = (int)$vid;
		if(($this->pid == '3001' && $this->softversion == '1.3.0') || ($this->pid == '3001' && $this->softversion == '1.3.1'))
		{
			$set['specialty'] = '';
			$set['thread'] = $specialty;
		}
		else
		{ 
			if($specialty)
			{
				$set['specialty'] = $specialty;
			}

			if($thread)
			{
				$set['thread'] = $thread;
			}
			else
			{
				$set['thread'] = $this->get_thread($specialty);
			}
		}
		
		$set['add_time'] = time();
		$set['cellphone'] = $cellphone;
		$set['invite_code'] = $invite_code;
		$set['platform'] = $this->platform;
		$set['productid'] = $this->pid;
		$set['softversion'] = $this->softversion;
		$set['device_id'] = $this->pid == "3001" ? ($this->imei ? $this->imei : $this->idfa)  : $this->idfa;
		$set['ipaddress'] = $this->clientip;
        $set['practice_hospital'] = $practice_hospital;
        $set['hospital_relate'] = $hospital_relate;
        $set['truename'] = $truename;
		ci_load_once('posttitlem');
        $set['post_title'] = $this->posttitlem->getPosttitleID($post_title);
		$set['source'] = $source;

		$this->db->set($set);
		$this->db->insert('ml_fellow');
        $insert_sql = $this->db->last_query();
		$user_id = $this->db->insert_id();
		$userInfo = $this->getUserInfoById($user_id);
		if($userInfo && $user_id)
		{
			$minsertuserinfo = $userInfo;
			$minsertuserinfo['user_id'] = (string)$user_id;
//			$this->cimongo->insert('member',$minsertuserinfo);

//			//添加用户默认订阅信息
//			$get_default_rss = explode(',', $this->get_default_rss($minsertuserinfo['thread']));
//
//			foreach ($get_default_rss as $value) {
//				$this->rssm->add_rss($user_id,$value);
//			}
            //生成token
            $this->uid = $user_id;
            $token = $this->authenticatem->create_token($user_id);

			return array('code' => 0,'response' => array("access_token" => $token,"user_id" => $user_id,"username" => $username,"email" => $email,"specialty" => $specialty,"isBound" => 0));
		}else
		{
            //注册失败时  写个日志
            w_log("insert_id is ".$user_id);
            w_log("user_reg is ".json_encode($userInfo));
            w_log("insert_sql is ".$insert_sql);
			return array('code' => -6,'tips' => '注册失败');
		}
	}

	//获取用户新文类
    public function get_thread($specialty)
    {
    	$keshi = array(
    		"001"=>"-1",
			"002"=>"-2",
			"003"=>"126",
			"004"=>"93",
			"005"=>"149",
			"006"=>"119",
			"007"=>"133",
			"008"=>"129",
			"009"=>"125",
			"010"=>"105",
			"011"=>"121",
			"012"=>"124",
			"013"=>"131",
			"014"=>"118",
			"015"=>"135",
			"016"=>"136",
			"017"=>"130",
			"018"=>"92",
			"019"=>"123",
			"020"=>"132",
		);

		return $keshi[$specialty];
    }

    //获取用户分类下的 默认订阅
    public function get_default_rss($thread)
    {
    	$keshi = array(
    		"-1"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,105,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,135,136,143,144",//医学生

			"-2"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,105,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,135,136,143,144",//实习医生

    		"93"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104",//大内科

			"95"=>"95,116,130",//呼吸内科

			"101"=>"101,141,110,130",//消化内科

			"99"=>"99,96,113",//神经内科

			"102"=>"102,115,116,123",//心内科

			"100"=>"100,109",//肾内科

			"98"=>"98,114",//内分泌科

			"94"=>"94,106",//风湿科

			"103"=>"103,133",//血液科

			"92"=>"92",//传染科

			"97"=>"97,93,95,101,99,102,100,98,94,103",//老年病科

			"91"=>"91,125",//变态反应科

			"96"=>"96,99",//精神科

			"104"=>"104,99,133",//医学遗传科

			"149"=>"106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149",//大外科

			"106"=>"106,94",//骨科

			"110"=>"110,141,148",//普通外科

			"141"=>"141,101,130",//肝胆外科

			"116"=>"116,102,115",//心胸外科

			"113"=>"113,99",//神经外科

			"109"=>"109,100",//泌尿外科

			"114"=>"114,98",//腺体外科

			"115"=>"115,102,116",//血管外科

			"142"=>"142,105",//头颈外科

			"108"=>"108,143",//颌面外科

			"112"=>"112,131",//烧伤外科

			"107"=>"107",//矫形外科

			"148"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,105,118,120,121,122,123,124,125,126,127,128,129,130,131,132,133,135,136,143,144",//小儿外科

			"117"=>"117",//整形外科

			"111"=>"111,131",//器官移植

			"119"=>"119,133",//妇产科

			"133"=>"133,103,119",//儿科

			"128"=>"128",//眼科

			"105"=>"105,108,142",//耳鼻喉科

			"143"=>"143,108",//口腔科

			"125"=>"125,91",//皮肤科

			"123"=>"123,102,99",//介入科

			"130"=>"130",//肿瘤科

			"136"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104",//中医科

			"121"=>"121,99,102,149,106,110,141,116,108,148",//急诊医学

			"129"=>"129,144,154",//医学影像科

			"154"=>"154",//超声

			"144"=>"144",//核医学科

			"122"=>"122",//检验科

			"124"=>"124,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,119",//麻醉科

			"118"=>"118",//病理科

			"135"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,105,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,135,136,143,144",//护理科

			"120"=>"120,130",//姑息医学

			"127"=>"127,99,113",//理疗康复科

			"126"=>"91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,110,111,112,113,114,115,116,117,141,142,148,149,105,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,135,136,143,144",//全科医学

			"131"=>"131,111",//重症监护

			"132"=>"132",//其它
		);
		//处于 -1 -2 （医学生实习生），其他科室改成一一对应
		if($thread == '-1' || $thread == '-2')
		{
			return $keshi[$thread];
		}

		return $thread;
    }

	public function userLogin($email,$passwd)
	{
		if(!$email || !$passwd)
		{
			return array('code' => -1,'tips' => '请完善您的登陆信息');
		}

		if(isemail($email))
		{
			$userInfo = $this->getUserInfoByEmail($email);
		}
		else if(iscellphone($email))
		{
			$userInfo = $this->getUserInfoByCellphone($email);
		}
		else
		{
			$userInfo = $this->getUserInfoByUserName($email);			
		}
		$md5pwd = md5($passwd);
		if($userInfo && $userInfo[0])
		{
			$passwd = $userInfo[0]['password'];
			if($md5pwd == $passwd)
			{
				$user_info = $userInfo[0];

				//修改缓存
				$mc = $this->cache->memcached;
				if(!$this->cache->memcached->is_supported())
		    	{
		    		$result = array("code" => -3,'tips' => "缓存未开启");
		    	}
                $userid = $user_info['id'];
	    		$key2 = self::USERINFO_BYID_KEY.$userid;
	    		$mc->delete($key2);
                //生成token
                $token = $this->authenticatem->create_token($user_info['id']);

				// 2.2.0 以后版本 用户没有订阅话题,强制订阅全部
				if (version_compare($this->softversion, '2.2.0') >= 0) {
					$this->load->model('rssm');
					$this->rssm->rss_topic($userid);
				}

				return  array('code' => 0,'response' => array("access_token" => $token, "user_id" => $user_info['id'],"username" => $user_info['username'],"email" => $user_info['email'],"thread" => $user_info['thread'],"specialty" => $user_info['specialty'],"isBound" => $user_info['isBound']));
			}else
			{
				return array('code' => -5,'tips' => '账户或者密码错误');
			}
		}else
		{
			//return array('code' => -3,'tips' => '登陆失败');
			return array('code' => -3,'tips' => '用户不存在');
		}
	}

	public function findPwd($email)
	{
		if(!$email)
		{
			return array('code' => -1,'tips' => '请完善您的登陆信息');
		}

		if(!isemail($email))
		{
			return array('code' => -2,'tips' => '邮箱格式不正确');
		}
		$userInfo = $this->getUserInfoByEmail($email);
		if($userInfo && $userInfo[0])
		{
			$user_id = $userInfo[0]['id'];
			$newpassword = random(8,1);
			$newmd5passwd = md5($newpassword);
			$this->db->set('password',$newmd5passwd);
			$this->db->where('id',$user_id);
			$this->db->update('ml_fellow');
//			$this->cimongo->where(array('user_id',(string)$user_id))->set(array('password' => $newmd5passwd))->update('member');
			$mail_content = '<html>';
			$mail_content .= '<head>';
			$mail_content .= '</head>';
			$mail_content .= '<body>';
			$mail_content .= '<div style="width:80%;margin:50px auto;background-color:#f7f7f7;padding:20px;">';
			$mail_content .= '<p style="border:1px solid #efefef;background-color:#ffffff;padding:50px 30px;">';
			$mail_content .= '<strong style="font-size:14px;line-height:30px;color:#333333;font-family:arial,sans-serif;">'.$userInfo[0]['username'].'</strong>,您好：<br /><br />';
			$mail_content .= '感谢您使用轻盈医学服务,您的密码已经重置，新密码为:<br />';
			$mail_content .= '<span style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;">'.$newpassword.'</span><br />';
			$mail_content .= '请及时登录轻盈医学并修改密码<br /><br /><br />';
			$mail_content .= '此致<br /><br />';
			$mail_content .= '轻盈医学团队<br /><br />';
			$mail_content .= '</p>';
			$mail_content .= '</div>';
			$mail_content .= '</body>';
			$mail_content .= '</html>';
			$subject = "【轻盈无限】重置密码";
			$this->phpmail->send($userInfo[0]['email'],$userInfo[0]['username'],$subject,$mail_content);
			return array('code' => 0,'tips' => '重置密码成功，请您查收邮件');
		}else
		{
			return array('code' => -3,'tips' => '邮箱不存在');
		}
	}
    public function send_code_email($email)
    {
        if(!$email)
        {
            return array('code' => -1,'tips' => '邮件不能为空');
        }
        $code = $this->utilm->get_yanzheng_code($email,6,$this->prefix,60*60);
        if(!isemail($email))
        {
            return array('code' => -2,'tips' => '邮箱格式不正确');
        }
        $userInfo = $this->getUserInfoByEmail($email);
        if($userInfo && $userInfo[0])
        {
            $mail_content = '<html>';
            $mail_content .= '<head>';
            $mail_content .= '</head>';
            $mail_content .= '<body>';
            $mail_content .= '<div style="width:80%;margin:50px auto;background-color:#f7f7f7;padding:20px;">';
            $mail_content .= '<p style="border:1px solid #efefef;background-color:#ffffff;padding:50px 30px;">';
            $mail_content .= '<strong style="font-size:14px;line-height:30px;color:#333333;font-family:arial,sans-serif;">'.$userInfo[0]['username'].'</strong>,您好：<br /><br />';
            $mail_content .= '感谢您使用轻盈医学服务,您的密码找回验证码为:<br />';
            $mail_content .= '<span style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;">'.$code.'</span><br />';
            $mail_content .= '有效期为1小时，请及时使用<br /><br /><br />';
            $mail_content .= '此致<br /><br />';
            $mail_content .= '轻盈医学团队<br /><br />';
            $mail_content .= '</p>';
            $mail_content .= '</div>';
            $mail_content .= '</body>';
            $mail_content .= '</html>';
            $subject = "【轻盈无限】验证码";
            $this->phpmail->send($userInfo[0]['email'],$userInfo[0]['username'],$subject,$mail_content);
            return array('code' => 0,'tips' => '验证码发送成功，请您查收邮件');
        }else
        {
            return array('code' => -3,'tips' => '邮箱不存在');
        }
    }
	public function changePwd($user_id,$oldpassword,$password)
	{
		if(!$user_id || !$oldpassword || !$password)
		{
			return array('code' => -1,'tips' => '对不起，信息缺失');
		}		
		$userInfo = $this->getUserInfoById($user_id);
		if($userInfo)
		{
			$nold = md5($oldpassword);
			if($nold == $userInfo['password'])
			{
				$inputpasswdmd5 = md5($password);
				$this->db->set('password',$inputpasswdmd5);
				$this->db->where('id',$userInfo['id']);
				$this->db->update('ml_fellow');
//				$this->cimongo->where(array('user_id' => (string)$user_id))->set(array('password' => $inputpasswdmd5))->update('member');

				ci_load_once('authenticatem');
				$this->authenticatem->expire_token($user_id);

				return array('code' => 0,'tips' => '修改密码成功，请退出账号重新登录');
			}else
			{
				return array('code' => -1,'tips' => '原始密码错误');
			}
		}
		return array('code' => -1,'tips' => '修改密码失败');
	}


	public function setnewpwd($cellphone,$newpwd)
	{
		if(!$cellphone || !$newpwd)
		{
			return array('code' => -1,'tips' => '对不起，信息缺失');
		}		
		$userInfo = $this->getUserInfoByCellphone($cellphone);
		if($userInfo && $userInfo[0])
		{
            $user_id =  $userInfo[0]['id'];
			$inputpasswdmd5 = md5($newpwd);
			$this->db->set('password',$inputpasswdmd5);
			$this->db->where('id',$userInfo[0]['id']);
			$this->db->update('ml_fellow'); 
			return array('code' => 0,'tips' => '修改密码成功');
		}
		return array('code' => -1,'tips' => '修改密码失败');
	}
    public function setnewpwd_byemail($email,$newpwd)
    {
        if(!$email || !$newpwd)
        {
            return array('code' => -1,'tips' => '对不起，信息缺失');
        }
        $userInfo = $this->getUserInfoByEmail($email);
        if($userInfo && $userInfo[0])
        {
            $user_id =  $userInfo[0]['id'];
            $inputpasswdmd5 = md5($newpwd);
            $this->db->set('password',$inputpasswdmd5);
            $this->db->where('id',$userInfo[0]['id']);
            $this->db->update('ml_fellow');
//            $this->cimongo->where(array('user_id' => (string)$user_id))->set(array('password' => $inputpasswdmd5))->update('member');
            return array('code' => 0,'tips' => '修改密码成功');
        }
        return array('code' => -1,'tips' => '修改密码失败');
    }

	public function getUserInfo($user_id, $nocache=0)
	{
        if($this->uid == $user_id)
        {
            $nocache = 1;
        }
		$mc = $this->cache->memcached;
    	$key = self::USERINFO_ALL_KEY . $user_id;

    	if(!$this->cache->memcached->is_supported())
    	{
    		$result = array("code" => -3,'tips' => "缓存未开启");
			return array();
    	}

		$data_content = $mc->get($key);
		if($data_content && $nocache == 0)
		{
			$user_info = $data_content;
		}
		else
        {
            $usertable = 'ml_fellow.id,ml_fellow.head_ico,ml_fellow.email,ml_fellow.user_level,ml_fellow.is_student,ml_fellow.practice_hospital,ml_fellow.username,ml_fellow.truename,ml_fellow.zip_code,ml_fellow.sex,ml_fellow.age,ml_fellow.thread,ml_fellow.specialty,ml_fellow.academy,ml_fellow.year_admission,ml_fellow.major,ml_fellow.hospital,ml_fellow.cellphone,ml_fellow.post_title,ml_fellow.isBound,ml_fellow.verified_status,ml_fellow.admin_level,ml_fellow.is_show_truename,ml_fellow.expert_info,ml_fellow.hospital_relate,ml_fellow.add_time';
            $usertable .= ',ml_specialty.specialty_name AS specialty';
            $usertable .= ',ml_thread.thread_name AS thread_name';
            $this->db->select($usertable)->from('ml_fellow');
            $this->db->join('ml_specialty', 'ml_fellow.specialty=ml_specialty.specialty_code', 'left');
            $this->db->join('ml_thread', 'ml_fellow.thread=ml_thread.id', 'left');
            $this->db->where('ml_fellow.id', $user_id);
            $query = $this->db->get()->result_array();
            if ($query && $query[0]) {
                $user_info = $query[0];
                $mc->save($key, $user_info, 5 * 60);
            }
        }
        if($user_info)
        {
            if (($this->pid == "2002" && version_compare($this->softversion, "1.7.0") > 0) || ($this->pid == "3001" && version_compare($this->softversion, "1.5.0") > 0)) {
                $user_info['verified_status'] = $user_info['verified_status'];
            } else {
                //如果是旧版本的 认证状态  学生认证改成 认证中
                $user_info['verified_status'] = $user_info['verified_status'] == 5 ? 2 : $user_info['verified_status'];
            }

			if (!isset($this->threadm)) {
				$this->load->model('threadm');
			}
			$user_info["thread_name"] = $this->threadm->get_thread_name($user_info["thread"]);
            $user_info["thread_name_only"] = $this->threadm->get_thread_name($user_info["thread"]);//留一个原始的科室字段

            $user_info['hospital_code']= $user_info['hospital_relate'];
            $user_info['is_expert'] = $user_info['user_level'] ? 1 : 0;  //根据用户级别来判断是否为专家  如果以后修改了用户级别 就修改判断条件
            $user_info['head_ico'] = ret_fullpath_url($user_info['head_ico']); // 获取头像更新

            if ($user_info['is_expert'] != 1 && $user_info['is_show_truename'] != 1 && $this->uid != $user_info['id']) {
                $user_info['truename'] = "";
            }
            //实名
            if ($user_info['is_show_truename'] == 1) {
                if ($user_info['truename'] && strcmp($user_info['truename'], $user_info['username']) != 0 && $this->uid != $user_id) {
                    $user_info['username'] = $user_info['truename'] . '「' . $user_info['username'] . '」';
                }
            }

            $user_info['truename'] = $user_info['truename'] ? $user_info['truename'] : '';
			$user_info['post_title'] = $this->transPostTitle($user_info['post_title']);

            //认证用户展示医院
            if ($user_info['verified_status'] == 3) {

                //取认证医院
                if (is_numeric($user_info['practice_hospital'])) {
                    $verified_info = $this->userm->verified_info($user_id);
                    $user_info['practice_hospital'] = $verified_info['hospital'];
                }

                //展示职称
                if(version_compare($this->softversion, "1.9.4") >= 0) {

                    $user_info['thread_name'] = $user_info['thread_name'] . ' ' . $user_info['post_title'];
                }
            }


            //如果是专家添加专家信息
            if ($user_info['user_level'] == 5) {
                $user_info['expert_info'] = $this->get_expert_info($user_id);
            }
//				$this->load->model("ucenterm");
//				$exp_level = $this->ucenterm->getUserExpLevel($user_id);
//				$user_info['exp_value'] = $exp_level["exp"];
//				$user_info['exp_level'] = $exp_level["level"];
        }
        else {
            $user_info = array();
        }


		return $user_info;
	}

	public function get_expert_info($uid)
	{
        $expert_info = $this->expertm->get_expert_info($uid);
        if($expert_info)
        {
            //避免出现  字符串null
            $goodat = $expert_info['goodat'] ? $expert_info['goodat'] : '';
            $experience = $expert_info['experience'] ? $expert_info['experience'] : '';
            $social_service = $expert_info['social_service'] ? $expert_info['social_service'] : '';
            $return = array(
                array("title"=>"擅长：","content"=>$goodat),
                array("title"=>"经历：","content"=>$experience),
                array("title"=>"社会任职：","content"=>$social_service),
            );
        }
		else
        {
            $return = array(
                array("title"=>"擅长：","content"=>''),
                array("title"=>"经历：","content"=>''),
                array("title"=>"社会任职：","content"=>''),
            );
        }
		return $return;
	}

	public function editUser($userid,$data)
	{
		ci_load_once('posttitlem');

		foreach($data AS $key => $value)
		{
			if($key == 'head_ico')
			{
				continue;
			}

            //如果是有非法字符
			if($ilegel = checkstesec($value))
			{
				$result = array("code" => -1,'tips' => '含有非法字符" '.$ilegel.'"');//这里改为提示用户那里错误
				return $result;
			}

		}
		$userinfo = $this->getUserInfoById($userid,1);
		if(!$userinfo)
		{
			return array('code' => -2,'tips' => '用户修改失败，不存在该用户');
		}
		if($data['username'] && $data['username'] != $userinfo['username'])
		{
			$checkusername = $this->getUserInfoByUserName($data['username']);
			if($checkusername && $checkusername[0])
			{
				return array('code' => -4,'tips' => '昵称已被占用');
			}
		}else
		{
			unset($data['username']);
		}
        //如果是修改真实姓名，医院，科室，职称，需要重新认证

        // 客户端传入的 posttitle 为字符串, 需转为数字
		$data['post_title'] = $this->posttitlem->getPosttitleID($data['post_title']);


        //不能要版本判断 不然老用户会自动修改重要信息 而不重新认证
        if($userinfo['user_level'] != 5) // 专家修改信息不需要重新认证
        {
			$user_posttitle_id = $this->posttitlem->getPosttitleID($userinfo['post_title']);

			if(strcmp($data['truename'], $userinfo['truename']) != 0 || strcmp($data['thread'], $userinfo['thread']) != 0 || strcmp($data['practice_hospital'], $userinfo['practice_hospital']) != 0 || ($user_posttitle_id != $data['post_title']) )
            {
                $white_cell = array('18659968822');
                $cellphone = $userinfo['cellphone'];

                if(!in_array($cellphone, $white_cell))
                {
                    if(version_compare($this->softversion,'2.2.0') >= 0)
                    {
						$truename = (strcmp($data['truename'], $userinfo['truename']) != 0) ? $data['truename'] : $userinfo['truename'];

						// 有手机号和真实姓名 直接插入认证信息
                        if ($cellphone && $truename) {
						
                            //改成服务端来插入认证信息 而不是客户端来提交
                            $data['verified_status'] = 2;
                            $this->verifiedm->verified_status_tofail_for_modifyuserinfo($userid);  //这里需要把以前提交的所有等待认证的修改为认证失败
                            $verified_data = [];
                            $verified_data['type'] = 1;
                            $verified_data['sex'] = $userinfo['sex'];
                            $verified_data['post_title'] = ($user_posttitle_id != $data['post_title']) ? $data['post_title'] : $user_posttitle_id;
                            $verified_data['truename'] = $truename;
                            $verified_data['hospital'] = (strcmp($data['practice_hospital'], $userinfo['practice_hospital']) != 0) ? $data['practice_hospital'] : $userinfo['practice_hospital'];
                            $verified_data['hospital_relate'] = (strcmp($data['hospital_relate'], $userinfo['hospital_relate']) != 0) ? $data['hospital_relate'] : $userinfo['hospital_relate'];
                            $verified_data['thread'] = (strcmp($data['thread'], $userinfo['thread']) != 0) ? $data['thread'] : $userinfo['thread'];
                            $verified_data['user_id'] = $this->uid;
                            $verified_data['addtime'] = time();
                            $this->verifiedm->insert_verified_log($verified_data);

                        } else { // 没有手机号 ,如果之前认证成功直接改为 未认证

                            if (in_array($userinfo['verified_status'], array(3,5))) {
                                $this->userm->update_verified_status($userid, 1);
                            }

                        }

                    }
                    else
                    {
                        $data['verified_status'] = 1;//重新认证
                        $this->verifiedm->verified_status_tofail_for_modifyuserinfo($userid);  //这里需要把以前提交的所有等待认证的修改为认证失败
                    }

                }

            }
        }
		$this->db->where('id',$userid);
		$this->db->update('ml_fellow',$data);
		$ismofidy = $this->db->affected_rows();
		if($ismofidy)
		{
			$userinfo = $this->getUserInfo($userid,1);

			//修改缓存
			$mc = $this->cache->memcached;
			if(!$this->cache->memcached->is_supported())
	    	{
	    		$result = array("code" => -3,'tips' => "缓存未开启");
	    	}

    		$key = self::USERINFO_BYID_KEY. $userid;
    		$mc->delete($key);
            //更新IM头像昵称
            $this->imapim->exec_update_userinfo($userid);

            $this->load->model("jfpointsm");
            $userinfo['jfpoints'] = $this->jfpointsm->get_uid_jfpoints($userid);
            //ios1.9.5版本 积分显示会显示成  男女
            if($userinfo['jfpoints'] == 0 || $userinfo['jfpoints'] == 1 || $userinfo['jfpoints'] == 3)
            {
                $userinfo['jfpoints'] = " ".$userinfo['jfpoints'];
            }

			return array('code' => 0,'userinfo' => $userinfo);
		}else
		{
			return array('code' => -3,'tips' => '修改信息与原有信息一致');
		}
	}

	public function get_one_user_4_search($user_id,$observer_id='',$isCache=0)
	{
		$userinfo = array();

        $this->load->model('specialtym');
        $row = $this->getUserInfoById($user_id,$isCache);
        $new = $this->specialtym->get_thread_list();
        $old = $this->specialtym->get_specialt_list();

        if($row)
        {
            $data_content = array();
			$data_content['id'] = $row['id'];
            $data_content['practice_hospital'] = $row['practice_hospital'];

            $data_content['username'] = $row['username'];

            $post_title = $this->transPostTitle($row['post_title']);
            $data_content['post_title'] = $post_title ;

            //认证用户展示医院
            if($row['verified_status'] == 3)
            {
                $verified_info = $this->verified_info($user_id);
                $hospital =  $verified_info['hospital'];
                if(!$hospital || $row['user_level'] == 5)
                {
                    $hospital = $row['practice_hospital'];
                }
                $data_content['practice_hospital'] = $hospital;


                if($row['is_show_truename']) {
                    if ($row['truename'] && strcmp($row['truename'], $row['username']) != 0) {
                        $data_content['username'] = $row['truename'] . '「' . $row['username'] . '」';
                    } else {
                        $data_content['username'] = $row['username'];
                    }
                }

                if(version_compare($this->softversion, '1.9.3') <= 0)
                {
                    $data_content['specialty_name'] = $hospital.' '.$data_content['specialty_name'];
                }
                else
                {
                    $data_content['specialty_name'] = $data_content['specialty_name'].' '.$post_title;
                }
            }

			/*$data_content['is_show_truename'] = $row['is_show_truename'];*/

			if($row['thread'] == "-1")
			{
				$data_content['specialty_name'] = "医学生";
			}
			else if($row['thread'] == "-2")
			{
				$data_content['specialty_name'] = "实习生";
			}
			else
			{
				$data_content['specialty_name'] = $new[$row['thread']] ? $new[$row['thread']]['thread_name'] :  $old[$row['specialty']]['specialty_name'];
			}
			$data_content['specialty_name'] = $data_content['specialty_name'] . ' ' . $post_title;

			$data_content['head_ico'] = $row['head_ico'];
			$data_content['verified_status'] = $row['verified_status'];
			$data_content['admin_level'] = $row['admin_level'];
			$data_content['is_expert'] = $row['user_level'] ? 1 : 0;  //根据用 户级别来判断是否为专家  如果以后修改了用户级别 就修改判断条件

            if($data_content['is_expert'] == 1)
            {
                $data_content['truename'] = $row['truename'] ? $row['truename'] : '';
                $data_content['expert_info'] = $row['expert_info'] ? $row['expert_info'] : '';
			} else {
				$data_content["post_title"] = "";
				$data_content["expert_info"] = "";
			}

            $data_content['thread'] = $row['thread'];
			$data_content['registrationID'] = $row['registrationID'];

			$userinfo = $data_content;
		}
		// 观察者与被观察者为同一人时 返回 0
		if($user_id == $observer_id)
		{
			$follow_status = 0;
		}
		else
		{
			$follow_status = $this->followm->get_follow_status($observer_id, $user_id);
		}
		$userinfo['follow_status'] = $follow_status;


		return $userinfo;
	}


	//判断用户是否为版主   并返回级别
	public function is_admin($user_id)
	{
		$result = $this->db->where(array("user_id"=>$user_id))->get("ml_leader")->result_array();
		return $return = $result ? $result[0]['level'] : FALSE;
	}

	public function checkcellphone($nocheckhpone,$cellphone)
	{
        //白名单用户不检查是否注册过 直接发短信
		if(in_array($cellphone,$nocheckhpone))
		{
			return False;
		}
		$exist = $this->db->select()->from('ml_fellow')->where('cellphone',$cellphone)->get()->result_array();
		if($exist && $exist[0])
		{
			return True;
		}else
		{
			return False;
		}
	}

	public function checkDeviceIdNums($idfa)
	{
		$this->db->select('COUNT(*) AS num')->from('ml_fellow');
		$this->db->where('device_id',$idfa);
		$query = $this->db->get()->result_array();
		$num = $query && $query[0] ? $query[0]['num'] : 0;
		return $num;
	}

	public function searchUser($keyword,$page = 1,$perpage = 20,$observer_id=0,$type=0)
	{
		if(!$keyword)
		{
			return array();
		}
        $sql = 'SELECT id as user_id FROM ml_fellow WHERE ';
        if($type == 1)
        {
            $sql = $sql."user_level = 5 AND (username like '%".$keyword."%' OR truename like '%".$keyword."%')";
        }
        else if($type == 2)//只返回坐诊专家
        {
            $sql = "SELECT ml_specialist.user_id FROM ml_specialist LEFT JOIN ml_fellow ON  ml_specialist.user_id = ml_fellow.id WHERE ml_specialist.is_service = 1 AND (ml_fellow.username like '%".$keyword."%' OR ml_fellow.truename like '%".$keyword."%')";
        }
        else
        {
            $sql = $sql."username like '".$keyword."%' OR truename like '".$keyword."%'";
        }
		if($page == 1)
		{
			$start = 0;
		}else
		{
			$start = ($page - 1) * $perpage;
		}

        $sql = $sql.' limit '.($start ? $start.', ' : '').$perpage;
//		$this->db->limit($perpage,$start);
        return $this->db->query($sql)->result_array();
	}

	public function update_cellphone($cellphone,$user_id)
	{
		$this->db->set("cellphone",$cellphone)->where("id",$user_id)->update("ml_fellow");
	}

    //更新用户是否完善过状态
    public function update_complete_profile($user_id)
    {
        $this->db->set("complete_profile",1)->where("id",$user_id)->update("ml_fellow");
    }

	//获取用户是否有设备id
	public function is_have_device()
	{
		return $is_device = $this->db->select("device_id")->where(array("id"=>$this->uid))->get("ml_fellow")->result_array();
	}

	//更新用户设备
	public function update_user_device($device_id,$platform)
	{
		$key = "device_" . $platform . '_' . $device_id;
		$cache = $this->mc->get($key);
		$result = false;
		if (!$cache) {
			$result = $this->db->set(array("device_id" => $device_id, "platform" => $platform, "productid" => $this->pid, "softversion" => $this->softversion, "ipaddress" => $this->clientip))->where(array("id" => $this->uid))->update("ml_fellow");

			if ($result) {
				$this->mc->save($key, $result, 60 * 60);
			}
		}
		return $result;
	}

	public function update_registrationID($registrationID,$uid)
	{
		$key = "registrationid_" . $registrationID . '_' . $uid;
		$cache = $this->mc->get($key);
		if (is_bool($cache) && $cache == false) {
			$userinfo = $this->db->select('registrationID')->where('id', $uid)->get('ml_fellow')->row_array();

			if ($userinfo['registrationID'] != $registrationID) {
				//更新数据
				$this->db->set("registrationID", $registrationID)->where("id", $uid)->update("ml_fellow");

				if ($registrationID) {
					$this->mc->save($key, $registrationID, 15 * 60);
				}
			}
		}
	}


	//开启实名认证
	public function update_show_truename($user_id,$status)
	{
		$mc = $this->cache->memcached;
        $key1 = self::USERINFO_BYID_KEY.$user_id;
        $key2 = self::USERINFO_ALL_KEY . $user_id;

        if(!$this->cache->memcached->is_supported())
    	{
    		$result = array("code" => -3,'tips' => "缓存未开启");
    	}
        $mc->delete($key1);
        $mc->delete($key2);
		return $this->db->set("is_show_truename",$status)->where("id",$user_id)->update("ml_fellow");
    }

	/**
	 * 获取用户的邀请码
	 * @param $user_id
	 * @return mixed
	 */
	public function get_uid_invite_code($user_id)
	{
		$mc = $this->cache->memcached;
    	$key = 'searchuser_invite_code_' . $user_id;

		$invite_code = $mc->get($key);
        if(!$invite_code) {
			$return = $this->db->select("invite_code")->where("id",$user_id)->get("ml_invite_code")->row_array();
			if ($return && $return['invite_code']) {
				$invite_code = $return['invite_code'];
				$mc->save($key,$invite_code, 600);
			}
        }

		return $invite_code;
	}

	// 根据用户id批量取用户信息
	public function getUserInfoByIds($ids, $nocache=0)
	{
		if (empty($ids)) {
			return [];
		}

		$lst_cache = [];
		$lst_no_cache = [];

		// 没被缓存的id
		$ids_no_cache = [];

		// 拿到缓存的部分
		if(!$nocache) {
			foreach ($ids as $id) {
				$key = self::USERINFO_BYID_KEY . $id;
				$info_cache = $this->mc->get($key);
				if (empty($info_cache)) {
					$ids_no_cache[] = $id;
				} else {
					$lst_cache[$id] = $info_cache;
				}
			}
		} else {
			$ids_no_cache = $ids;
		}

		$result = $lst_cache;

		if ($ids_no_cache) {
			$data_content = $this->db->select()->from("ml_fellow")->where_in("id", $ids_no_cache)->get()->result_array();
			foreach($data_content as $userinfo) {
				$uid = $userinfo["id"];
				$lst_no_cache[$uid] = $userinfo;
                $userinfo['head_ico'] = ret_fullpath_url($userinfo['head_ico']);

                $result[$uid] = $userinfo;

				$key = self::USERINFO_BYID_KEY . $uid;
				$this->mc->save($key, $userinfo, 5*60);
			}
		}

		return $result;
	}

    //取用户认证医院
    public function verified_info($user_id)
    {
        $mc = $this->cache->memcached;
        $this->cache->memcached->is_supported();
        if($this->pid == 2002 && version_compare($this->softversion, "1.9.3")<0) {
            $key = 'userm_verified_info' . $this->pid . $user_id;
        }
        else
        {
            $key = 'userm_verified_info'. $user_id;
        }
        $info = $mc->get($key);

        if(!$info)
        {
            $query = $this->db->select()->where("user_id",$user_id)->order_by('id','desc')->get("ml_verified_log")->result_array();
            $info = !empty($query) ? $query[0] : array();
            $mc->save($key,$info,30*30);
        }
        return $info;
    }



	/**
	 * 资料是否已完善
     * change 2016年1月22日10:43:23
	 */
	public function is_profile_completed($new_profile) {
		$keys = array(
            "head_ico",
            "username",  //昵称
            "truename", //真实姓名
			"thread",  //科室
            "sex",   //性别
            "age",  //年龄
            "academy", //毕业院校
			"practice_hospital",  //执业医院
            "hospital", //工作地点
            "post_title", //职称
			"zip_code",  //邮编
            );

		foreach ($keys as $key) {
			//w_log('$keys is '.$key.'       '.$new_profile[$key]);
			if (empty($new_profile[$key]) and $new_profile[$key] !== '0') {//这里不能用empty 因为 sex为女的时候 值是0  会判断出错
				//w_log('error key is '.$key);
				return false;
			}
		}

		return true;
	}

	// 根据用户 ID 数组获取用户 push 注册 ID
	public function selectRegIDArrByUserIDArr($user_id_arr) {
		$data = $this->db->select("registrationID, id")->where_in("id", $user_id_arr)->get("ml_fellow")->result_array();

		$result =  array();
		foreach ($data as $itm) {
			if (!isset($itm["registrationID"])) {
				continue;
			}

			$result[$itm["registrationID"]] = $itm;
		}

		return $result;
	}

	/**
	 * 更新用户表 认证次数
	 * @param int $user_id
	 * @return bool
	 */
	public function update_verified_total($user_id = 0)
	{
		if (!$user_id) return false;
		return $this->db->set('verified_total', 'verified_total + 1', false)->set(array('verified_status' => 2))->where(array('id' => $user_id))->update('ml_fellow');
	}


	/**
	 * 根据用户id批量取用户信息
	 * @param $where_in
	 * @param $where
	 * @param null $order
	 * @param $observer_id
	 * @param $limit: null or [$page, $page_size]
	 * @param $result_key
	 * @return array
	 */
	public function getUserBasicInfo($where_in, $where, $order=null, $observer_id, $limit = null, $result_key = '')
	{
		if (empty($where_in) && empty($where)) {
			return [];
		}

		$this->db->select("id,username,truename,head_ico,user_level,admin_level,verified_status,practice_hospital,post_title,thread,is_show_truename");
		$this->db->from("ml_fellow");
		if ($where_in) {
			foreach ($where_in as $k => $v) {
				$this->db->where_in($k, $v);
			}
		}
		if ($where) {
			$this->db->where($where);
		}
		if ($order) {
			foreach ($order as $k => $v) {
				$this->db->order_by($k, $v);
			}
		}
		if ($limit)
		{
			$page = $limit[0];
			$page_size = $limit[1];
			$this->db->limit($page_size, ($page-1) * $page_size);
		}
		$query = $this->db->get();
//		print_r($this->db->last_query());exit;
		if (!$query) {
			return [];
		}
		$data = $query->result_array();

		$result = array();
		foreach ($data as $k => $v) {
			$user_info = $this->transFellowInfo($v, $observer_id);

			if ($result_key) {
				$result[$v[$result_key]] = $user_info;
			}
			else {
				$result[] = $user_info;
			}
		}

		return $result;
	}
	
	
	public function isShowTruename($username, $truename, $is_show_truename, $is_me = 0)
	{
		if (!$is_show_truename || $is_me || !$truename || strcmp($truename, $username) == 0) {
			return false;
		}
		return true;
	}


	public function transUsername($username, $truename, $is_show_truename, $is_me = 0)
	{
		if (!$this->isShowTruename($username, $truename, $is_show_truename, $is_me)) {
			return $username;
		}
		return "{$truename}「{$username}」";
	}


	public function transTruename($truename)
	{
		return $truename ? $truename : "";
	}


	public function transIsExpert($user_level)
	{
		return $user_level == 5 ? 1 : 0;
	}


	public function transHeadIcon($head_ico)
	{
		return ret_fullpath_url($head_ico);
	}


	public function transPostTitle($post_title)
	{
		ci_load_once('posttitlem');
		return $this->posttitlem->getPosttitleName($post_title);
	}

	public function transVerifiedStatus($verified_status)
	{
		if (($this->pid == "2002" && version_compare($this->softversion, "1.7.0") > 0) || ($this->pid == "3001" && version_compare($this->softversion, "1.5.0") > 0)) {
			//
		} else {
			//如果是旧版本的 认证状态  学生认证改成 认证中
			$verified_status = $verified_status == 5 ? 2 : $verified_status;
		}
		return $verified_status;
	}

	public function transSpecialtyName($thread_name, $post_title)
	{
		if (is_numeric($thread_name)) {
			ci_load_once('threadm');
			$thread_name = $this->threadm->get_thread_name($thread_name);
		}
		$post_title = $this->transPostTitle($post_title);
		
		return $thread_name . ' ' . $post_title;
	}


	/**
	 * 将详细的用户信息转化为较短的用于展示的信息
	 * 必要的字段有:id,username,truename,head_ico,user_level,admin_level,verified_status,practice_hospital,post_title,thread,is_show_truename
	 * @param $user_info
	 * @param $observer_id
	 * @param null $my_follows
	 * @return array
	 */
	public function transFellowInfo($user_info, $observer_id, $my_follows = null)
	{
		$is_me = ($observer_id && $user_info["id"] == $observer_id) ? true : false;
		$post_title = $this->transPostTitle($user_info["post_title"]);
		$follow_status = 0;
		if (!$is_me && $my_follows && isset($my_follows[$user_info["id"]])) {
			$follow_status = $my_follows[$user_info["id"]];
		}
		$is_expert = $this->transIsExpert($user_info["user_level"]);
		$expert_info = $is_expert ? $user_info["expert_info"] : "";

		$show_info = array(
			"id" => $user_info["id"],
			"username" => $this->transUsername($user_info["username"], $user_info["truename"], $user_info["is_show_truename"], $is_me),
			"truename" => $this->transTruename($user_info["truename"]),
			"head_ico" => ret_fullpath_url($user_info['head_ico']),
			"post_title" => $post_title,
			"is_expert" => $is_expert,
			"practice_hospital" => $user_info["practice_hospital"],
			"specialty_name" => $this->transSpecialtyName($user_info["thread"], $post_title),
			"verified_status" => $this->transVerifiedStatus($user_info["verified_status"]),
			"thread" => strval($user_info["thread"]),
			"admin_level" => $user_info["admin_level"],
			"expert_info" => $expert_info,
			"follow_status" => $follow_status,
		);

		return $show_info;
	}


	/**
	 * 取少量用于展示的用户信息
	 * @param $user_ids
	 * @param $observer_id
	 * @return array
	 */
	public function getUserInfoByIDsForShow($user_ids, $observer_id = 0)
	{
		$user_info_arr = $this->getUserInfoByIds($user_ids);

		$my_follows = array();
		if ($observer_id) {
			ci_load_once('followm');
			$my_follows = $this->followm->getUserRelationship($observer_id);
		}

		$result = array();
		foreach ($user_info_arr as $uid => $v) {
			$user_info = $this->transFellowInfo($v, $observer_id, $my_follows);
			$result[$v["id"]] = $user_info;
		}

		return $result;
	}

	/**
	 * 获取用户热门标签
	 * @param $thread
	 */
	public function get_hot_tags($thread)
	{
		$res = array();
        if($thread)
		{
          $res = $this->db->select('b.id,b.tag_name')
			              ->from('ml_hot_tags as a ')
			              ->join('ml_tags as b','a.tag_id = b.id','left')
			              ->where('a.type_id',$thread)
			              ->get()->result_array();
			return $res;

		}else{
			return $res;
		}
	}

    /**
     * 更改 用户认证状态
     * @param $user_id
     * @param int $verified_status
     */
    public function update_verified_status($user_id, $verified_status = 1)
    {
        $data = array('verified_status' => $verified_status);
        return $this->db->where(array('id' => $user_id))->update('ml_fellow', $data);
    }
	/**
	 * 用户邀请列表
	 */
	public function get_invite_list($user_id)
	{
		$data = array();
		$this->load->model('Followm');
		$res =  $this->db->select('a.id')
						 ->from('ml_fellow as a ')
						 ->join('ml_invite_code as b','a.invite_code=b.invite_code','left')
						 ->where('b.id',$user_id)
						 ->get()->result_array();
		$code = $this->db->select('invite_code')->from('ml_invite_code')->where('id',$user_id)->get()->row_array();
		$data['invite'] = $code['invite_code'];
		if($res)
		{
			foreach ($res as $k =>$v)
			{
				$userInfo = $this->getUserInfo($v['id']);
				$data['list'][$k]['id']                = $userInfo['id'];
				$data['list'][$k]['head_ico']          = $userInfo['head_ico'];
				$data['list'][$k]['post_title']        = $userInfo['post_title'];
                $data['list'][$k]['username']          = $userInfo['username'];
				$data['list'][$k]['practice_hospital'] = $userInfo['practice_hospital'];
				$data['list'][$k]['thread_name']       = $userInfo['thread_name'];
				$data['list'][$k]['user_level']        = $userInfo['user_level'];
				$data['list'][$k]['verified_status']   = $userInfo['verified_status'];
				$data['list'][$k]['admin_level']       = $userInfo['admin_level'];
				$data['list'][$k]['addtime']           = $userInfo['add_time'];
				$data['list'][$k]['follow_status']  = $this->Followm->get_follow_status($user_id,$v['id']);
			}
		}else{
			$data['list'] = array();
		}

		return $data;
	 }

	/**
	 * 获取用户钱包信息
	 * @param $user_id
	 * @return array
	 */
	public function get_user_wallet_passwd($user_id)
	{
         $res = $this->db->select('pay_passwd')->from('ml_fellow')->where('id',$user_id)->get()->row_array();
		 return $res['pay_passwd'];
	}



	/**
	 * 更新支付密码
	 * @param $user_id
	 * @param $passwd
	 * @return object
	 */
	public function update_user_wallet_passwd($user_id,$passwd)
	{
		$info = array('pay_passwd'=>$passwd);
		$res  = $this->db->set($info)->where('id',$user_id)->update('ml_fellow');
		return $res;
	}


    /**
     * @param int $user_id
     * @param string $passwd
     * @param string $old_password_hash 原支付密码
     * @param int $no_check_limit 默认需要检查失败次数
     * @return array|bool
     */
	public function checkUserWalletPasswd($user_id, $passwd, $old_password_hash, $no_check_limit = 0)
    {
        if (! $no_check_limit) {
            ci_load_once('redis', 'cache');
            $key_lock = USER_WALLET_LOCK . $user_id;
            if ($this->redis->get($key_lock)) {
                return ['message' => '您的支付密码已经被锁定,请24小时后再试', 'code' => '-1'];
            }
        }

        $count_key = USER_WALLET_COUNT . $user_id;
        // 检查密码无误, 直接返回
        if (password_verify($passwd, $old_password_hash)) {
            $this->redis->delete($count_key);
            return false;
        }
        if ($no_check_limit) {
            return ['message' => '原始支付密码输入有误', 'code' => '-1'];
        }

        // 支付密码有误, 增加失败次数
        $count = $this->redis->get($count_key);
        if ($count) {
            $count += 1;
        } else {
            $count = 1;
        }
        $this->redis->save($count_key, $count, USER_WALLET_LOCK_EXPIRE_TIME);

        // 输错 ERROR_TRY_COUNT_PAY_PASSWD 次以上, 锁定24小时
        if ($count >= self::ERROR_TRY_COUNT_PAY_PASSWD) {
            $this->redis->save($key_lock, 1, USER_WALLET_LOCK_EXPIRE_TIME);
            return array('message' => '您的支付密码已经被锁定, 请24小时后再试。', 'code' => '-1');
        }
        $msg = sprintf("支付密码不正确，您还可以输入 %d 次", (self::ERROR_TRY_COUNT_PAY_PASSWD - $count));
        return array('message' => $msg, 'code' => '-1');
    }
}
